package com.vinci.login.controller;


import com.vinci.config.MD5Util;
import com.vinci.login.entity.TbLoginUser;
import com.vinci.login.entity.TokenUser;
import com.vinci.login.service.TbLoginUserService;
import com.vinci.util.Constants;
import com.vinci.util.JsonObject;
import com.vinci.util.TokenUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;

import javax.servlet.http.HttpSession;


/**
 * <p>
 * 用户表 前端控制器
 * </p>
 *
 * @author 淼
 * @since 2021-12-10
 */
@RestController
@Slf4j
public class TbLoginUserController {
    @Autowired
    private TbLoginUserService tbLoginUserService;

    @Autowired
    private TokenUtil tokenUtil;


    /**
     * 请求登入
     *
     * @return
     */
    @GetMapping("/loginuser")
    public JsonObject loginuser(@RequestParam("userName") String userName, @RequestParam("passWord") String passWord) {
        JsonObject jsonObject = new JsonObject();

        try {
            if(StringUtils.isEmpty(userName) || StringUtils.isEmpty(passWord)){
                jsonObject.setMsg("错误");
                jsonObject.setCode("B0001");
                return jsonObject;
            }
            //密码加密
            String s = MD5Util.formPassToDBPass(passWord, "1a2b3c4d");
            //获取用户信息
            TbLoginUser loginuser = tbLoginUserService.loginuser(userName, s);
            //判断用户名和密码是否为空
            if (loginuser != null) {
                //获取用户密码
                String passWord1 = loginuser.getPassWord();
                //比较数据库密码和加密后的密码
                if (passWord1.equals(s)) {
                    //创建json数据
                    jsonObject.setCode(Constants.OK_COOE);
                    jsonObject.setMsg("成功");
                    String token = tokenUtil.getToken(loginuser.getUserId(),loginuser.getRealName());
                    TokenUser tokenUser = new TokenUser();
                    tokenUser.setToken(token);
                    List<TokenUser> list = new ArrayList<>();
                    list.add(tokenUser);
                    jsonObject.setData(list);
                    return jsonObject;
                }
            }else{
                jsonObject.setMsg("B0001");
                return jsonObject;
            }
        } catch (Exception e) {
            jsonObject.setMsg("B0001");
        }
        return jsonObject;
    }


    /**
     * 注销用户 注销按钮
     *
     * @return
     */
    @GetMapping("/loginout")
    public String loginout(HttpSession session) {

        //把存到session中的用户删掉
        session.removeAttribute("loginuser");
        //注销之后返回到登入页面
        return "loginuser";
    }


}

